package com.shd.edanpei.photo;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import com.shd.edanpei.R;
import com.shd.edanpei.util.IntentUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import io.reactivex.functions.Consumer;

/**
 * Created by mc on 2018/12/7.
 * yang-wen-wen
 */

public class PhotoManager {

    private final String[] permissions =
            {Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private Activity mActivity;
    private RxPermissions mRxPermissions;

    public PhotoManager(Activity activity) {
        this.mActivity = activity;
        this.mRxPermissions = new RxPermissions(activity);
    }

    public void savePhoto(final Bitmap bitmap) {
        checkPermissions(new CheckListener() {

            @Override
            public void allow() {
                new SaveImageTask().execute(bitmap);
            }
        });
    }

    private class SaveImageTask extends AsyncTask<Bitmap, Void, String> {


        @Override
        protected String doInBackground(Bitmap... params) {
            String result = mActivity.getResources().getString(R.string.save_picture_failed);
            try {
                String sdcard = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera";


                File file = new File(sdcard);
                if (!file.exists()) {
                    file.mkdirs();
                }

                File imageFile = new File(file.getAbsolutePath(), new Date().getTime() + ".jpg");
                FileOutputStream outStream = null;
                outStream = new FileOutputStream(imageFile);
                Bitmap image = params[0];
                image.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                outStream.flush();
                outStream.close();
                result = mActivity.getResources().getString(R.string.save_picture_success, file.getAbsolutePath());

                MediaStore.Images.Media.insertImage(mActivity.getContentResolver(), image, "", "");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                for (int i = 0; i < params.length; i++) {
//                    params[i].recycle();
//                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(mActivity.getApplicationContext(), result, Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 检查权限
     */
    private void checkPermissions(final CheckListener listener) {

        mRxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //有权限
                            listener.allow();
                        } else {
                            //无权限
                            showDialog();
                        }
                    }
                });

    }

    private void showDialog() {
        new AlertDialog.Builder(mActivity)
                .setTitle("权限被禁止")
                .setMessage("存储权限已禁止，请到权限设置中打开！")
                .setNegativeButton("取消", null)
                .setPositiveButton("去打开", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mActivity.startActivity(IntentUtils.getAppDetailSettingIntent());
                    }
                }).show();

    }

    private interface CheckListener {

        void allow();
    }
}
